package com.jinyu.jyly.net.api;


import android.annotation.SuppressLint;
import android.util.Log;

import com.jinyu.jyly.AppApplication;
import com.jinyu.jyly.global.GlobalConstants;
import com.jinyu.jyly.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;


/**
 * @Company
 * @user zhangjinbo
 * @Description ok管理类
 */
public class OkHttpManager {

    private static OkHttpClient mOkHttpClient;
    private static String sSystemModel;
    private static String sPropertyAgent;
    private static String sAppVersionName;


    public static OkHttpClient getInstance() {

        if (mOkHttpClient == null) {
            synchronized (OkHttpManager.class) {
                if (mOkHttpClient == null) {
                    //log拦截器
                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    final long currentTimeMillis = System.currentTimeMillis();

                    /**
                     * 设置缓存的第一步,,,,这里只是设置了缓存的目录以及缓存的大小
                     */

                    mOkHttpClient = new OkHttpClient.Builder()
                            //配置证书
//                            .sslSocketFactory(createSSLSocketFactory(),)
                            .hostnameVerifier(new TrustAllHostnameVerifier())
                            .connectTimeout(15, TimeUnit.SECONDS) // 设置超时时间
                            .readTimeout(15, TimeUnit.SECONDS) // 设置读取数据时间
                            .addInterceptor(loggingInterceptor) // 设置log拦截器
                            .retryOnConnectionFailure(true) // 设置出现错误进行重新连接
                            .addInterceptor(new Interceptor() {
                                @Override
                                public Response intercept(Chain chain) throws IOException {
                                    Request original = chain.request();
                                    HttpUrl url = original.url();

                                    String token = (String) SharedPreferencesUtils.getParam(AppApplication.getAppContext(), GlobalConstants.LOGIN_TOKEN, "");
                                    Request.Builder requestBuilder = original.newBuilder();
//                                    requestBuilder.addHeader("Content-Type", "application/json;charset=UTF-8")
//                                            .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),
//                                                    bodyToString(original.body())))//关键部分，设置requestBody的编码格式为json
//                                            .build();
                                    Log.e("token11",token);
                                    Log.e("接口",url.toString());
                                    requestBuilder.addHeader("token",token);
                                    Request request = requestBuilder.build();
                                    return chain.proceed(request);
                                }
                            })
                            .build();
                }
            }
        }
        return mOkHttpClient;
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    @SuppressLint("TrulyRandom")
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return sSLSocketFactory;
    }

    private static class TrustAllManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }


}
